<?php 
define("SCOOPIT_REQUEST_URL", "https://www.scoop.it/oauth/request");
define("SCOOPIT_AUTHORIZE_URL", "https://www.scoop.it/oauth/authorize");
define("SCOOPIT_ACCESS_URL", "https://www.scoop.it/oauth/access");
define("CALLBACK_URL", "http://".$_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);

class ScoopitOAuth {

	private $db;
	private $oauth;
	
	
	function __construct($db, $options) {
		$this->db = $db;
		$this->oauth = new OAuth($options['scoopit_key'],$options['scoopit_secret']);
	}
	
	function login() {
		$requestToken = $this->oauth->getRequestToken(SCOOPIT_REQUEST_URL);
		$this->db->setSecret(serialize($requestToken['oauth_token_secret']));
			
		$params = array('oauth_token' => $requestToken['oauth_token'], 'oauth_callback' => CALLBACK_URL);
		$url = SCOOPIT_AUTHORIZE_URL . '?' . http_build_query($params);
		echo "<p><a href=\"$url\">Login</a> to Scoop.It</p>";
	}
	
	function startThirdLeg() {
		if ($this->db->getAccessToken() == null) :
			$this->oauth->setToken($_GET['oauth_token'], unserialize($this->db->getSecret()) );
			$accessToken = $this->oauth->getAccessToken(SCOOPIT_ACCESS_URL);
			$this->db->setAccessToken(serialize($accessToken));
		endif;
	}
	
	function showLogin() {
		if ($this->db->getAccessToken() == null)
			return true;
		
		if ($this->isValidAccessToken())
			return false;
		else
			return true;
	}
	
	private function isValidAccessToken() {
		$accessToken = unserialize($this->db->getAccessToken());
		$this->oauth->setToken($accessToken['oauth_token'], $accessToken['oauth_token_secret']);
		$this->oauth->fetch(BASEURL. '/api/1/test', null, 'GET', array('Accept-Encoding' => 'gzip,deflate'));
		$response = $this->oauth->getLastResponseInfo();
		if ($response['http_code'] != 200) {
			$this->db->setAccessToken(null);
			return false;
		}	
		return true;	
	}
}
?>